//
//  main.cpp
//  DayTimeServer1
//
//  Created by Ge Jian Feng on 14-5-24.
//  Copyright (c) 2014年 Ge Jian Feng. All rights reserved.
//

#include <iostream>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <time.h>

// Define
#define MAXLINE                     4096
#define bzero(addr, len)            memset(addr, 0, len)

int main(int argc, const char * argv[])
{
    // Initialize variable
    int                         socketId, connId;
    struct sockaddr_in          servaddr;
    char                        buff[MAXLINE];
    time_t                      ticks;
    int                         status;
    
    // Create socket
    socketId = socket(AF_INET, SOCK_STREAM, 0);
    if (socketId < 0) {
        std::cerr << "Create socket error!" << std::endl;
        exit(1);
    }
    
    // Initialize IP address
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(13000);
    servaddr.sin_len = sizeof(servaddr);
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    bzero(&servaddr.sin_zero, sizeof(servaddr.sin_zero));
    
    // Bind socket
    status = bind(socketId, (struct sockaddr*)&servaddr, sizeof(servaddr));
    if (status < 0) {
        std::cerr << "Fail to bind socket!" << std::endl;
        exit(1);
    }
    
    // Listen socket
    if (listen(socketId, 1024)) {
        std::cerr << "Listen error!" << std::endl;
        exit(1);
    }
    
    // Process logic
    for (;;) {
        connId = accept(socketId, (struct sockaddr*)NULL, NULL);
        ticks = time(NULL);
        snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
        write(connId, buff, strlen(buff));
        close(connId);
    }
    
    return 0;
}